package com.icim.csot.exporter.service;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.icim.core.service.IFtpService;
import com.icim.csot.exporter.tx.csotshipping.CsotShippingO;
import com.icim.csot.exporter.xmlentity.CsotShippingAbnormalCodeList;
import com.icim.csot.exporter.xmlentity.CsotShippingBlockXmlEntity;
import com.icim.csot.exporter.xmlentity.CsotShippingBoxXmlEntity;
import com.icim.csot.exporter.xmlentity.CsotShippingDataXmlEntity;
import com.icim.csot.exporter.xmlentity.CsotShippingPalletXmlEntity;
import com.icim.dao.RetBoxDao;
import com.icim.dao.RetCusPrdInDao;
import com.icim.dao.RetCusPrdIndtAblistDao;
import com.icim.dao.RetCusPrdIndtDao;
import com.icim.dao.RetPrdGrdInfoDao;
import com.icim.dao.RetPrdInfoDao;
import com.icim.dao.RetWoDao;
import com.icim.entity.Ret_box;
import com.icim.entity.Ret_cus_prd_in;
import com.icim.entity.Ret_cus_prd_indt_ablist;
import com.icim.entity.Ret_prd_grd_info;
import com.icim.entity.Ret_prd_info;
import com.icim.entity.Ret_wo;
import com.icim.util.FileUtil;
import com.icim.util.GzCompressUtil;
import com.icim.util.TimeUtil;
import com.icim.util.XmlConvertUtil;
import static com.icim.def.ComDef.*;

@Service
public class ShippingDataService {

    private final Logger logger = LoggerFactory.getLogger(ShippingDataService.class);
    @Resource
    private RetBoxDao retBoxDao;

    @Resource
    private RetPrdInfoDao retPrdInfoDao;

    @Resource
    private RetCusPrdIndtAblistDao retCusPrdIndtAblistDao;

    @Resource
    private RetCusPrdIndtDao retCusPrdIndtDao;

    @Resource
    private RetPrdGrdInfoDao retPrdGrdInfoDao;

    @Resource
    private RetCusPrdInDao retCusPrdInDao;
    
    @Resource 
    private RetWoDao retWoDao;

    @Resource
    private IFtpService ftpService;

    public String subMainProc(String palletId) throws Exception {
        String rtnMsg = "";
        try {
            logger.info(palletId);
            rtnMsg =  subMainProc2(palletId);
        } catch (Exception e) {
            logger.error(e.toString());
            CsotShippingO outTrx = new CsotShippingO();
            outTrx.setTrx_id("CSOTSHIPPING");
            outTrx.setType_id("O");
            outTrx.setRtn_code("9999999");
            outTrx.setRtn_mesg(e.toString());
            rtnMsg = outTrx.toString();
            throw e;
        }
        return rtnMsg;
    }

    public String subMainProc2(String palletId) throws Exception {

        CsotShippingO outTrx = new CsotShippingO();
        outTrx.setTrx_id("CSOTSHIPPING");
        outTrx.setType_id("O");
        outTrx.setRtn_code("0000000");
        outTrx.setRtn_mesg("SUCCESS");

        if (StringUtils.isEmpty(palletId)) {
            outTrx.setRtn_code("0000002");
            outTrx.setRtn_mesg("栈板ID不能为空");
            return XmlConvertUtil.obj2Xml(outTrx, "transaction");
        }

        CsotShippingDataXmlEntity shippingDataPallet = new CsotShippingDataXmlEntity();
        CsotShippingPalletXmlEntity shippingPalletXmlEntity = new CsotShippingPalletXmlEntity();
        shippingPalletXmlEntity.init();
        // 根据palletId找到箱子
        List<Ret_box> retBoxList = retBoxDao.getBoxList(palletId);
        if (retBoxList.isEmpty()) {
            outTrx.setRtn_code("999999");
            outTrx.setRtn_mesg("can not find any box by pallet id");
            return XmlConvertUtil.obj2Xml(outTrx, "transaction");
        }
        Ret_box firstBox = retBoxList.get(0);
        shippingPalletXmlEntity.setFACTORYNAME(CSOT_FACTORY_NAME);
        shippingPalletXmlEntity.setSHIPPINGPALLETNAME(palletId);// TODO

        shippingPalletXmlEntity.setOWNER_ID("");// TODO
        shippingPalletXmlEntity.setPRODUCTSPECNAME(firstBox.getMdl_id());
        shippingPalletXmlEntity.setX_PRODUCT_LAYOUT(0);// TODO
        shippingPalletXmlEntity.setY_PRODUCT_LAYOUT(0);// TODO
        shippingPalletXmlEntity.setBOXQUANTITY(retBoxList.size());
        shippingPalletXmlEntity.setPALLETCAPACITY(0);// TODO
        shippingPalletXmlEntity.setWORKORDERTYPE("PP");// TODO
        shippingPalletXmlEntity.setLOTTYPE("PP");// TODO

        shippingPalletXmlEntity.setTIMESTAMP(TimeUtil.getEvtTime());
        shippingPalletXmlEntity.setCOMMENT("");// TODO

        List<String> boxIdList = new ArrayList<String>();
        for (Ret_box ret_box : retBoxList) {
            boxIdList.add(ret_box.getBox_id());
        }

        List<Ret_cus_prd_in> mtrlBoxList = retCusPrdInDao.getMtrlBoxList(boxIdList);
        Map<String, Ret_cus_prd_in> mtrlBoxMap = new HashMap<String, Ret_cus_prd_in>();
        for (Ret_cus_prd_in retCusPrdIn : mtrlBoxList) {
            mtrlBoxMap.put(retCusPrdIn.getMtrlBoxId(), retCusPrdIn);
        }

        List<CsotShippingBoxXmlEntity> boxXmlEntityList = new ArrayList<CsotShippingBoxXmlEntity>();
        for (Ret_box retBox : retBoxList) {

            shippingPalletXmlEntity.setPALLET_ID(retBox.getShip_pallet_name());

            CsotShippingBoxXmlEntity boxXmlEntity = new CsotShippingBoxXmlEntity();
            boxXmlEntity.init();
            
            if(!mtrlBoxMap.isEmpty()){
            	boxXmlEntity.setBOXID(mtrlBoxMap.get(retBox.getBox_id()).getBoxPhyId());
            }
            if(!mtrlBoxMap.isEmpty()){
            	shippingPalletXmlEntity.setPALLETCAPACITY(mtrlBoxMap.get(retBox.getBox_id()).getMtrlPalletCapacity());
            }
            boxXmlEntity.setBLOCKQUANTITY(retBox.getPrd_qty());
            boxXmlEntity.setBOXCAPACITY(retBox.getStd_qty());
            boxXmlEntity.setSHIPPINGBOXNAME(retBox.getShip_box_id());

            // 根据箱子找到玻璃
            List<Ret_prd_info> retPrdInfoList = retPrdInfoDao.getSheetList(retBox.getBox_id());

            List<CsotShippingBlockXmlEntity> blockXmlEntityList = new ArrayList<CsotShippingBlockXmlEntity>();

            for (Ret_prd_info retPrdInfo : retPrdInfoList) {

                CsotShippingBlockXmlEntity blockXmlEntity = new CsotShippingBlockXmlEntity();
                blockXmlEntity.init();
                blockXmlEntity.setBLOCKNAME(retPrdInfo.getPrd_seq_id());
                String soId = retPrdInfo.getSo_id_fk();
                List<Ret_wo> retSoList = retWoDao.getWo(soId);
                blockXmlEntity.setWORKORDERNAME(retSoList.isEmpty() ? "" : retSoList.get(0).getSo_id());
                blockXmlEntity.setSN(retPrdInfo.getPrd_seq_id());
                blockXmlEntity.setGRADE(retPrdInfo.getGrade());

                boxXmlEntity.setGRADE(retPrdInfo.getGrade());

                shippingPalletXmlEntity.setGRADE(retPrdInfo.getGrade());
                shippingPalletXmlEntity.setX_PRODUCT_LAYOUT(retPrdInfo.getX_axis_cnt());
                shippingPalletXmlEntity.setY_PRODUCT_LAYOUT(retPrdInfo.getY_axis_cnt());
                shippingPalletXmlEntity.setOWNER_ID(retPrdInfo.getGroup_id());

                // 拼凑layout_ox

                List<Ret_prd_grd_info> gradeList = retPrdGrdInfoDao.getGrade(retPrdInfo.getPrd_seq_id());
                if (!gradeList.isEmpty()) {
                    blockXmlEntity.setLAYOUT_OX(gradeList.get(0).getPrd_seq_grd());
                }

                // 获取abnormal_code_list
                List<Ret_cus_prd_indt_ablist> retCusPrdIndtAblist = retCusPrdIndtAblistDao.getAbList(retPrdInfo
                        .getPrd_seq_id());
                
                CsotShippingAbnormalCodeList codeXmlEntity = new CsotShippingAbnormalCodeList();
                codeXmlEntity.init();

                if (!retCusPrdIndtAblist.isEmpty()) {
                    codeXmlEntity.setCODE(retCusPrdIndtAblist.get(0).getCode());
                    codeXmlEntity.setCODE_COMMENT(retCusPrdIndtAblist.get(0).getCodeDesc());
                }
                blockXmlEntity.setABNORMAL_CODE_LIST(codeXmlEntity);
                blockXmlEntity.setDEFECTCODE("");
                blockXmlEntity.setSLIM_FLAG(retPrdInfo.getGrade());

                blockXmlEntityList.add(blockXmlEntity);
            }

            boxXmlEntity.setBLOCKLIST(blockXmlEntityList);

            boxXmlEntityList.add(boxXmlEntity);
        }

        shippingPalletXmlEntity.setBOXLIST(boxXmlEntityList);

        shippingDataPallet.setBODY(shippingPalletXmlEntity);
        // 将对象转换成xml

        String xml = XmlConvertUtil.obj2Xml(shippingDataPallet, "MESSAGE");
        logger.info(xml);

        String localPath = ftpService.getFtpConfigure().getLocalTemporaryPath();
        String xmlFileName = localPath + "/" + palletId + ".XML";
        FileUtil.sting2File(xmlFileName, xml);
        // 压缩位gz包

        GzCompressUtil.compress(new File(xmlFileName));
        // 上传ftp

        String gzFileName = xmlFileName + ".gz";
        File gzFile = new File(gzFileName);
        ftpService.connect();
        ftpService.uploadFile(gzFile);
        ftpService.disconnectFtp();
        // TODO:报警

        return XmlConvertUtil.obj2Xml(outTrx, "transaction");
    }
}
